import axios from 'axios'
import { compress } from './pictureUtils.js'
import config from './config.js'
import { formatDate } from '@/utils/myUtils.js'
import { MessageBox, Message } from 'element-ui'
// 上传图片
export const uploadImg = function(fileList, keyPath, isCompress = true) {
  const that = this
  return new Promise((resolve, reject) => {
    if (fileList.length === 0) {
      resolve()
      return
    }
    const promises = []
    fileList.map(img => {
      console.info('img', img)
      const promise = new Promise(function(reso, reje) {
        if (img.raw) {
          console.log('图片过大:' + img.raw.size + ',去压缩')
          if (isCompress) {
            compressAvatard(img.raw, 1024 * 3, function(res) {
              ossUpload(res, keyPath, (data) => {
                console.info('data===>', data)
                img.url = data
                reso(data)
              })
            })
          } else {
            ossUpload(img.raw, keyPath, (data) => {
              img.url = data
              reso(data)
            })
          }
        } else {
          reso(img.url)
        }
      })

      promises.push(promise)
    })

    Promise.all(promises)
      .then(res => {
        console.info('图片上传res===>', res)
        resolve(res)
      }).catch(function(e) {
        console.info('e===>', e)
        reject()
      })
  })
}

const compressAvatard = function(file, kb, callback) {
  console.info('文件', file)
  console.info('大小', kb)
  console.info('方法', callback)
  const _this = this
  const raw = file.raw ? file.raw : file
  compress(raw, function(val) {
    // val是Blob类型，转换为file类型
    const newfile = new window.File([val], file.name, { type: raw.type })
    // newfile.uid = file.uid;
    // 压缩率过低则停止压缩, 防止死循环
    if ((newfile.size / 1024) > kb && (newfile.size / file.size < 0.9)) {
      console.log('图片过大:' + newfile.size + ',已压缩')
      compressAvatard(newfile, kb, callback)
    } else {
      callback(newfile)
      console.log('压缩后大小:' + newfile.size)
    }
  })
}

const ossUpload = function(filePath, keyPath, callback) {
  const aliyunFileKey = keyPath + new Date().getTime() + Math.floor(Math.random() * 150) + '.png'

  const formData = new FormData()
  formData.append('key', aliyunFileKey)
  formData.append('OSSAccessKeyId', config.OSSAccessKeyId)
  formData.append('success_action_status', 200)
  formData.append('signature', config.signature)
  formData.append('policy', config.policy)
  formData.append('file', filePath, filePath.name)

  axios.post(config.uploadImageUrl, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    const url = config.uploadImageUrl + aliyunFileKey
    callback && callback(url)
  })
}

// 上传文件
export const uploadFile = function(fileList, keyPath) {
  const that = this
  return new Promise((resolve, reject) => {
    if (fileList.length === 0) {
      resolve()
      return
    }
    const promises = []
    fileList.map(file => {
      const promise = new Promise(function(reso, reje) {
        if (file.raw) {
          ossUpFile(file.raw, keyPath, (data) => {
            file.url = data
            reso(data)
          })
        } else {
          reso(file.url)
        }
      })
      promises.push(promise)
    })

    Promise.all(promises)
      .then(res => {
        console.info('文件上传res===>', res)
        resolve(res)
      }).catch(function(e) {
        console.info('e===>', e)
        reject()
      })
  })
}
const ossUpFile = function(filePath, keyPath, callback) {
  const day = formatDate(new Date(), 'yyyy-MM-dd')
  const aliyunFileKey = keyPath + '/uploadFile/' + day + '/' + filePath.name

  const formData = new FormData()
  formData.append('key', aliyunFileKey)
  formData.append('OSSAccessKeyId', config.OSSAccessKeyId)
  formData.append('success_action_status', 200)
  formData.append('signature', config.signature)
  formData.append('policy', config.policy)
  formData.append('file', filePath, filePath.name)

  axios.post(config.uploadImageUrl, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    const url = config.uploadImageUrl + aliyunFileKey
    callback && callback(url)
  })
}
